<template>
  <Dialog :title="dialogTitle" width="70vw" v-model="dialogVisible">

    <!-- 维修申请单详细信息 -->
    <RepairInfoView ref="viewRef" />

    <el-form ref="formRef" size="large" :model="formData" :rules="formRules" label-width="120px"
      v-loading="formLoading">
      <el-divider content-position="left">故障信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="维修分类" prop="maintenanceId">
            <el-select filterable clearable v-model="formData.maintenanceId" placeholder="请选择">
              <el-option v-for="dict in maintenanceClassification" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>


        <el-col :span="8">
          <el-form-item label="开始时间1" prop="startTime">
            <el-date-picker disabled v-model="formData.startTime" type="datetime" value-format="x"
              placeholder="选择开始时间" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker disabled v-model="formData.endTime" type="datetime" value-format="x"
              placeholder="维修报工后自动填充" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="维修时长(分钟)" prop="repairDuration">
            <el-input disabled v-model="formData.repairDuration" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="维修成本(元)" prop="repairCost">
            <el-input v-model="formData.repairCost" placeholder="请输入维修成本(元)" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否解决" prop="resolved">
            <el-select v-model="formData.resolved" placeholder="请选择">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.IS_RESOLVED)" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="故障分析" prop="faultAnalysis">
            <el-input type="textarea" v-model="formData.faultAnalysis" placeholder="请输入故障分析" />
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="维修事项" prop="repairItem">
            <el-input type="textarea" v-model="formData.repairItem" placeholder="请输入维修事项" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">保 存</el-button>
      <el-button @click="reporting" type="primary" :disabled="formLoading">维修报工</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { RepairTaskApi, RepairTask } from '@/api/business/repairtask'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import RepairRequestForm from '../repairrequest/RepairRequestForm.vue'
import { FaultClassificationApi, FaultClassification } from '@/api/business/faultclassification'
import RepairInfoView from './RepairInfoView.vue'
import EquipmentInfoView from '../equipmentmanage/EquipmentInfoView.vue'
import { MaintenanceClassificationApi, MaintenanceClassification } from '@/api/business/maintenanceclassification'
import * as UserApi from '@/api/system/user'
import { dateFormatter, formatDate } from '@/utils/formatTime'

/** 维修任务 表单 */
defineOptions({ name: 'RepairTaskForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('维修报工') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  repairId: undefined,
  maintenanceId: undefined,
  equipmentId: undefined,
  startTime: undefined,
  endTime: undefined,
  repairDuration: undefined,
  repairCost: undefined,
  resolved: undefined,
  faultAnalysis: undefined,
  repairItem: undefined,
  status: undefined
})
const formRules = reactive({
  maintenanceId: [{ required: true, message: '维修分类不能为空', trigger: 'change' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  faultAnalysis: [{ required: true, message: '故障分析不能为空', trigger: 'blur' }],
  repairItem: [{ required: true, message: '维修事项不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  await initData()
  dialogVisible.value = true
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RepairTaskApi.getRepairTask(id)
      openViewDialog(formData.value.repairId)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RepairTask
    if (formType.value === 'create') {
      await RepairTaskApi.createRepairTask(data)
      message.success(t('common.createSuccess'))
    } else {
      await RepairTaskApi.updateRepairTask(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

//维修报工
const reporting = async () => {
  try {
    // 二次确认
    await message.confirm("确认维修报工?")
    //先更新任务单信息
    formData.value.status = 4
    const data = formData.value
    await RepairTaskApi.updateRepairTask(data)
    message.success("提交成功!")
    dialogVisible.value = false
    emit('success')
  } catch { }

}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    repairId: undefined,
    maintenanceId: undefined,
    equipmentId: undefined,
    startTime: undefined,
    endTime: undefined,
    repairDuration: undefined,
    repairCost: undefined,
    resolved: undefined,
    faultAnalysis: undefined,
    repairItem: undefined,
    status: undefined
  }
  formRef.value?.resetFields()
}

//维修详细信息
const viewRef = ref()

//维修申请详细信息
const openViewDialog = (id) => {
  viewRef.value.openDetailInfo(id, false)
}

//维修分类信息
const maintenanceClassification = ref([])

//用户列表
const userList = ref([])

const initData = async () => {
  maintenanceClassification.value = await MaintenanceClassificationApi.getMaintenanceClassificationList();
  userList.value = await UserApi.getSimpleUserList()

}


</script>
